<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Email extends AdminController{
	public $_validation = null;
	
	function __construct(){
		parent::__construct();
		$this->load->model('MEmail');
		
		$this->_validation = Array(
			array('field'=>'creator_id', 'label'=>'创建者', 'rules'=>'required|integer|max_length[11]')
			,array('field'=>'asin', 'label'=>'商品ASIN', 'rules'=>'trim|required|max_length[255]')
			,array('field'=>'name', 'label'=>'联系人姓名', 'rules'=>'trim|max_length[255]')
			,array('field'=>'profile', 'label'=>'联系人资料链接', 'rules'=>'trim|max_length[255]')
			,array('field'=>'country', 'label'=>'国家', 'rules'=>'max_length[4]')
			,array('field'=>'votes', 'label'=>'商品名称', 'rules'=>'trim|integer|max_length[4]')
			,array('field'=>'ranking', 'label'=>'排名', 'rules'=>'trim|integer|max_length[11]')
			,array('field'=>'email', 'label'=>'联系人邮箱', 'rules'=>'trim|required|max_length[255]')
			,array('field'=>'email_times', 'label'=>'发邮件次数', 'rules'=>'trim|integer|max_length[4]')
			,array('field'=>'email_last_time', 'label'=>'上次发邮件时间', 'rules'=>'trim|integer|max_length[11]')
			,array('field'=>'facebook', 'label'=>'Facebook', 'rules'=>'trim|max_length[255]')
			,array('field'=>'facebook_times', 'label'=>'facebook联系次数', 'rules'=>'trim|integer|max_length[4]')
			,array('field'=>'facebook_last_time', 'label'=>'上次facebook联系时间', 'rules'=>'trim|integer|max_length[11]')
			,array('field'=>'twitter', 'label'=>'Twitter', 'rules'=>'trim|max_length[255]')
			,array('field'=>'twitter_times', 'label'=>'Twitter联系次数', 'rules'=>'trim|integer|max_length[4]')
			,array('field'=>'twitter_last_time', 'label'=>'上次Twitter联系时间', 'rules'=>'trim|integer|max_length[11]')
			,array('field'=>'youtube', 'label'=>'Youtube', 'rules'=>'trim|max_length[255]')
			,array('field'=>'youtube_times', 'label'=>'Youtube联系次数', 'rules'=>'trim|integer|max_length[4]')
			,array('field'=>'youtube_last_time', 'label'=>'上次Youtube联系时间', 'rules'=>'trim|integer|max_length[11]')
			,array('field'=>'pinterest', 'label'=>'Pinterest', 'rules'=>'trim|max_length[255]')
			,array('field'=>'pinterest_times', 'label'=>'Pinterest联系次数', 'rules'=>'trim|integer|max_length[4]')
			,array('field'=>'pinterest_last_time', 'label'=>'上次Pinterest联系时间', 'rules'=>'trim|integer|max_length[11]')
			,array('field'=>'instagram', 'label'=>'Instagram', 'rules'=>'trim|max_length[255]')
			,array('field'=>'instagram_times', 'label'=>'Instagram联系次数', 'rules'=>'trim|integer|max_length[4]')
			,array('field'=>'instagram_last_time', 'label'=>'上次Instagram联系时间', 'rules'=>'trim|integer|max_length[11]')
			,array('field'=>'status', 'label'=>'邮箱状态', 'rules'=>'integer|required')
			,array('field'=>'remark', 'label'=>'备注信息', 'rules'=>'trim|max_length[255]')
			,array('field'=>'update_time', 'label'=>'更新时间', 'rules'=>'')
		);
		
		$this->load->model('MAdmin');
		$allReviewAdmins = $this->MAdmin->getAllReviewAdmin();
		$this->assign('allReviewAdmins', $allReviewAdmins);
		$this->assign('currentAdminId',$this->_user->id);
		$this->assign('currentAdminName',$this->_user->account);
		$this->assign('currentRoleId', $this->_user->role_id);
	}
	
	function index($asin=null){
		//$this->output->enable_profiler(TRUE);
		$this->load->library('FormFilter');
		$this->load->helper('formfilter');
		$this->formfilter->addFilter('email', 'where');
		$this->formfilter->addFilter('remark', 'like');
		$this->formfilter->addFilter('creator_id','where');
		$this->formfilter->addFilter('country','where');
		$this->formfilter->addFilter('status','where');
		if($asin!=null){
		    $this->formfilter->setFilterValue('asin', $asin);
		}
		$this->formfilter->addFilter('asin','where');
		
		if($begintime = filterValue('email_create_time_begin')){
		    $this->formfilter->addFilter('email_create_time_begin', 'where',array('emails.email_last_time >= ',strtotime($begintime.' 00:00:00')));
		}
		if($endtime = filterValue('email_create_time_end')){
		    $this->formfilter->addFilter('email_create_time_end', 'where',array('emails.email_last_time <= ',strtotime($endtime.' 23:59:59')));
		}
		
		$email_number_perpage = filterValue('email_number_perpage');
		$email_order_type = filterValue('email_order_type');
		
		$filterCount = $this->MEmail->getCount();  //过滤数量
		$limit = $this->pagination($filterCount,'',$email_number_perpage);
		$list = $this->MEmail->getList($limit,$email_order_type);
		
		$this->assign('list', $list);
		$this->assign('filterCount', $filterCount);
		$this->assign('totalCount', $this->MEmail->getTotalCount());
		$this->layout();
	}
	
	function add(){
	    $obj = $this->MEmail->createVo();
	    $this->load->library('form_validation');
	    $this->form_validation->set_rules($this->_validation);
	    if($this->form_validation->run()==TRUE){
	        $this->load->helper('populate');
	        $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
	        if($this->MEmail->add($newObj)){
	            successAndRedirect(l('edit_success'));
	        }else{
	            errorAndRedirect(l('data_fail'));
	        }
	    }
	    
	    $this->assign('obj', $obj);
	    $this->layout();
	}
	
	function edit($id){
	    if(!is_numeric($id)){
	        show_error(l('id_not_null'));
	    }
	    $obj = $this->MEmail->getOne(Array('id'=>$id));
	    if(!$obj){
	        errorAndRedirect('未找到定义！');
	    }
	    $this->editObj = $obj;
	    $this->load->library('form_validation');
	    $this->form_validation->set_rules($this->_validation);
	    if($this->form_validation->run()==TRUE){
	        $this->load->helper('populate');
	        $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
	        if($this->MEmail->update($newObj)){
	            successAndRedirect(l('edit_success'));
	        }else{
	            errorAndRedirect(l('data_fail'));
	        }
	    }
	    $this->assign('obj', $obj);
	    $this->layout();
	}
	
	function delete($id, $update_time){
	    if(!is_numeric($id) || !is_numeric($update_time)){
	        show_error(l('id_not_null'));
	    }
	    if(!$this->MEmail->delete($id, $update_time)){
	        errorAndRedirect(l('data_fail'));
	    }
	    successAndRedirect(l('delete_success'));
	}
	
	function ajaxTest(){
	    header('Access-Control-Allow-Origin: *');
	    echo "Hello world";
	}
	
	/**
	 * ajax 请求添加备注信息
	 */
	function ajaxAddRemark(){
	    $retObj = new stdClass();
	    if(!$this->p->edit){
	        $retObj->code = -9;
	        $retObj->message = "权限不足";
	        echo json_encode($retObj);
	        exit();
	    }
	    
	    $emailId = $this->input->post('emailId');
	    $obj = $this->MEmail->getOne(Array('id'=>$emailId));
	    if(!$obj){
	        $retObj->code = -2;
	        $retObj->message = "未找到记录";
	        echo json_encode($retObj);
	        exit();
	    }
	    $obj->remark = $this->input->post('remark');
	    if($this->MEmail->update($obj)){
	        $retObj->code = 1;
	        $retObj->message = "添加备注成功";
	        echo json_encode($retObj);
	        exit();
	    }else{
	        $retObj->code = -1;
	        $retObj->message = "添加备注失败";
	        echo json_encode($retObj);
	        exit();
	    }
	}
	
	/**
	 * ajax 请求增加邮箱使用次数
	 */
	function ajaxPlusUseEmailNum(){
	    $retObj = new stdClass();
	    if(!$this->p->edit){
	        $retObj->code = -9;
	        $retObj->message = "权限不足";
	        echo json_encode($retObj);
	        exit();
	    }
	    
	    $emailId = $this->input->post('emailId');
	    $obj = $this->MEmail->getOne(Array('id'=>$emailId));
	    if(!$obj){
	        $retObj->code = -2;
	        $retObj->message = "未找到记录";
	        echo json_encode($retObj);
	        exit();
	    }
	    $obj->email_times = $obj->email_times + 1;
	    $obj->email_last_time = time();
	    if($this->MEmail->update($obj)){
	        $retObj->code = 1;
	        $retObj->message = "使用成功";
	        $retObj->use_current_time = date("Y-m-d H:i:s",$obj->email_last_time);
	        echo json_encode($retObj);
	        exit();
	    }else{
	        $retObj->code = -1;
	        $retObj->message = "使用失败";
	        echo json_encode($retObj);
	        exit();
	    }
	}
	
	function postPlusUseEmailNum(){
	    if(!$this->p->edit){
	        //权限不足
	        show_error(l('user_has_nopower'));
	    }
	    if(!$this->input->post()){
	        show_error('提交数据错误！');
	    }
	    $email_ids = $this->input->post('ids');
	    $emailIdArr = explode(',', $email_ids);
	    if($this->MEmail->updateEmailsNum($emailIdArr)){
	        successAndRedirect('批量更新使用邮箱成功！');
	    }else{
	        errorAndRedirect('批量更新使用邮箱失败！');
	    }
	}
	
	/**
	 * ajax 查看指定email id的数据
	 * @param unknown $id
	 */
	function ajaxViewDetail($email_id){
	    if(!$this->p->read){
	        //权限不足
	        model_error(l('user_has_nopower'));
	    }
	    if(((int)$email_id) . '' !== $email_id){
	        model_error(l('id_or_updated_not_null'));
	    }
	    $obj = $this->MEmail->getOne(Array('id'=>$email_id));
	    if(!$obj){
	        model_error('未找到定义！');
	    }
	    
	    $this->assign('obj', $obj);
	    $this->assign('thisControllerName', '查看Email详情');
	    $this->layout_modal('modal-detail');
	}
	
	/**
	 * 
	 * @param unknown $ceping_id
	 */
	function handle_email($ceping_id){
	    $countSql = 'select count(id) as num from core_emails where creator_id=1';
	    $count = $this->db->query($countSql)->result();
	    echo "总共：".$count[0]->num."<br/>";
	    //查找符合条件的所有随机email
	    $sql = 'SELECT id FROM core_emails WHERE
		        id >= ( ( SELECT MAX( id ) FROM core_emails ) - ( SELECT MIN( id ) FROM core_emails ) ) * RAND( ) + ( SELECT MIN( id ) FROM core_emails ) 
		        AND creator_id = 1 
	            LIMIT 1034';
	    $emailIds = $this->db->query($sql)->result();
	    foreach ($emailIds as $k=>$emailId){
	        $updateSql = 'update core_emails set creator_id = '.$ceping_id.' where id = '.$emailId->id;
	        echo ($k+1)." = ".$updateSql." ";
	        $ret = $this->db->query($updateSql);
	        if($ret){
	            echo '<b style="color:green;">执行成功</b><br/>';
	        }else{
	            echo '<b style="color:red;">执行失败</b><br/>';
	        }
	    }
	    
	}
	
	
	/**
	 * 处理excel表导入
	 */
	function excelImportHandler(){
	    $redirectUrl = site_url($this->_thisModule.$this->_thisController);
	    if ($this->_user->role_id != 3 && $this->_user->role_id != 1){  //非测评组人员或超管
	        errorAndRedirect('非测评组人员或超管不能上传邮箱数据！！！',$redirectUrl);
	    }
	    
	    $config['upload_path'] = getcwd().DIRECTORY_SEPARATOR.'upload'.DIRECTORY_SEPARATOR.'excelfiles'.DIRECTORY_SEPARATOR;
	    $config['allowed_types'] = 'xls|xlsx';
	    $config['overwrite'] = false;
	    $config['max_size'] = 100000;
	    
	    $this->load->library('upload',$config);
	    if(!$this->upload->do_upload('excel_file')){
	        $error = $this->upload->display_errors();
	        errorAndRedirect($error,$redirectUrl);
	    }
	    $upload_data = $this->upload->data();
	    $file = $upload_data['full_path'];
	    
	    $this->load->library('PHPExcel');
	    $this->load->library('PHPExcel/IOFactory');
	    
	    $objPHPExcel = new IOFactory();    // 创建对象
	    
	    $readerType = $objPHPExcel::identify($file);
	    $objReader = $objPHPExcel::createReader($readerType);
	    $objPHPExcel = $objReader->load($file);    // 读文件
	    $objWorksheet = $objPHPExcel->getActiveSheet(0);
	    $highestRow = $objWorksheet->getHighestRow();  // 总行数
	    $highestColumn = $objWorksheet->getHighestColumn();    // 总列数
	    $highestColumnIndex = range('A', $highestColumn);
	    
	    // 从第二行开始，第一行一般是表头
	    for ($row = 2; $row <= $highestRow; $row++) {
	        $array = array();
	        foreach ($highestColumnIndex as $value) {
	            $address = $value . $row;
	            $array[] = $objWorksheet->getCell($address)->getFormattedValue();
	        }
	        $newItemArray = array(
	            $this->_user->id,
	            $array[0],
	            $array[1],
	            $array[2],
	            $array[3],
	            $array[4]==''?'0':$array[4],
	            $array[5],
	            $array[6],
	            $array[7],
	            $array[8],
	            $array[9],
	            $array[10],
	            $array[11],
	            $array[12],
	            time(),
	            time()
	        );
	        $sql = 'INSERT IGNORE INTO `core_emails` (`creator_id`,`asin`,`asin_group`,`name`,`profile`,`country`,`votes`,`ranking`,`email`,`facebook`,`twitter`,`youtube`,`pinterest`,`instagram`,`create_time`,`update_time`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
	        $this->db->query($sql,$newItemArray);
	    }
	    successAndRedirect('导入邮箱数据成功！');
	    
	}
}